import 'package:app_core/app_core.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:yh_core_flutter_project/project/common/api/login/user_api.dart';
import 'package:yh_core_flutter_project/project/common/extension/api_service.dart';
import '../../../router/app_routers.dart';
import 'email_code_page.dart';

enum ForgotPwdUpdateKey { email, password, confirmPassword, button, privacy }

class ForgotPwdLogic extends GetxController with CodeConfirmActionMixin {

  @override
  CodeConfirmAction get confirmAction => forgotPwd;

  @override
  String get email => emailController.text;

  @override
  CodeResendAction get resendAction => resendCode;

  @override
  String get title => "忘记密码"; 
  

  final emailController = TextEditingController();
  final emailFocusNode = FocusNode();

  final passwordController = TextEditingController();
  final passwordFocusNode = FocusNode();

  final confirmPasswordController = TextEditingController();
  final confirmPasswordFocusNode = FocusNode();

  // 密码和确认密码的可见性状态
  bool showPassword = false;
  bool showConfirmPassword = false;

  // 邮箱是否符合规则
  bool isEmailValid = true;
  bool isPasswordValid = true;
  bool isConfirmPasswordValid = true;

  bool get canSubmit =>
      emailController.text.isNotEmpty &&
      passwordController.text.isNotEmpty &&
      confirmPasswordController.text.isNotEmpty &&
      isEmailValid &&
      isPasswordValid &&
      isConfirmPasswordValid;

  // 监听文本变化
  @override
  void onInit() {
    super.onInit();
    emailController.addListener(
      () => update([ForgotPwdUpdateKey.email, ForgotPwdUpdateKey.button]),
    );
    emailFocusNode.addListener(() {
      if (!emailFocusNode.hasFocus) {
        validateEmail();
      }
      update([ForgotPwdUpdateKey.email]);
    });

    passwordController.addListener(
      () => update([ForgotPwdUpdateKey.password, ForgotPwdUpdateKey.button]),
    );
    passwordFocusNode.addListener(() {
      if (!passwordFocusNode.hasFocus) {
        validatePassword();
      }
      update([ForgotPwdUpdateKey.password]);
    });

    confirmPasswordController.addListener(
      () => update([ForgotPwdUpdateKey.confirmPassword, ForgotPwdUpdateKey.button]),
    );
    confirmPasswordFocusNode.addListener(() {
      if (!confirmPasswordFocusNode.hasFocus) {
        validateConfirmPassword();
      }
      update([ForgotPwdUpdateKey.confirmPassword]);
    });
  }

  @override
  void onClose() {
    // 释放控制器资源
    emailController.dispose();
    passwordController.dispose();
    confirmPasswordController.dispose();
    emailFocusNode.dispose();
    passwordFocusNode.dispose();
    confirmPasswordFocusNode.dispose();
    super.onClose();
  }

  // 切换密码可见性
  void togglePasswordVisibility() {
    showPassword = !showPassword;
    update([ForgotPwdUpdateKey.password]); // 更新 UI
  }

  // 切换确认密码可见性
  void toggleConfirmPasswordVisibility() {
    showConfirmPassword = !showConfirmPassword;
    update([ForgotPwdUpdateKey.confirmPassword]); // 更新 UI
  }

  // 邮箱输入框的验证逻辑
  void validateEmail() {
    final value = emailController.text;
    if (value.isEmpty || !GetUtils.isEmail(value)) {
      isEmailValid = false;
    } else {
      isEmailValid = true;
    }
    update([ForgotPwdUpdateKey.email]);
  }

  // 密码输入框的验证逻辑
  void validatePassword() {
    final value = passwordController.text;
    if (value.isEmpty) {
      isPasswordValid = false;
    } else {
      isPasswordValid =
          value.length >= 8 &&
          value.length <= 20 &&
          RegExp(r'[A-Za-z]').hasMatch(value) &&
          RegExp(r'[0-9]').hasMatch(value);
    }
    update([ForgotPwdUpdateKey.password]);
  }

  // 确认密码输入框的验证逻辑
  void validateConfirmPassword() {
    final value = confirmPasswordController.text;
    if (value.isEmpty || value != passwordController.text) {
      isConfirmPasswordValid = false;
    } else {
      isConfirmPasswordValid = true;
    }
    update([ForgotPwdUpdateKey.confirmPassword]);
  }

  // 登录逻辑
  void sendCode() async {
   final isOK = await resendCode();
    if (isOK) {
      Get.toNamed(
        AppRouters.emailCode.r,
        arguments: this,
      );
    }
  }

  void forgotPwd(String code) async {
    var email = emailController.text;
    var password = passwordController.text;
    YHSmartDialog.showLoading();
    final res = await UserApi.forgetPwd.request<dynamic>(
      params: {
        "email": email,
        "password": password,
        "code": code,
      },
    );
    YHSmartDialog.dismiss();
    // if (res.isOK) {
    //   YHSmartDialog.showMsg("重置密码成功");
    //   Get.until((route) => Get.currentRoute == AppRouters.login.r); // 返回到登录页面
    // }
  }

  Future<bool> resendCode()async{
    YHSmartDialog.showLoading();
    // final res = await UserApi.login.request<UserModel>(
    //   data: {...},
    //   fromJson: UserModel.fromJson,
    // );
    // final res = await UserApi.userList.request<List<UserModel>>(
    //   fromJson: UserModel.fromJsonList,
    // );
    // List<UserModel> users = res.data!;
    final res = await UserApi.sendEmailCode.request<dynamic>(
      params: {"email": emailController.text, "sendType": "forgotPwd"},
    );
    YHSmartDialog.dismiss();
    return true;
    // if (res.isOK) {
    //   YHSmartDialog.showMsg("验证码发送成功");
    //   return true;
    // } else {
    //  YHSmartDialog.showMsg(res.error?.message ?? "");
    //   return false;
    // }
  }
  
}